<?php
/**
 * Created by jinqiang on 2024/7/9 9:42.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Wms;


use App\Http\Models\Mysql\SsyAllocationReportingListTable;
use App\Http\Models\Mysql\SsyAllocationReportingTable;
use App\Http\Models\Mysql\SsyFeishuApprovalBindingTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Repository\FeishuRepository;
use Illuminate\Support\Facades\DB;

class BaociService
{
    public function search($param)
    {
        $conn = new SsyAllocationReportingListTable();
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', $param['status']);
        }
        if($param['number'] ?? ""){
            $conn = $conn->where('allocation_number', $param['number']);
        }
        if(isset($param['create_time']) && !empty($param['create_time'])){
            $conn = $conn->whereBetween('createtime', $param['create_time']);
        }
        if($param['add_user'] ?? ""){
            $name = auth()->guard("api")->user()->name;
            $conn = $conn->where('adduser', $name);
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        $allocationNumbers = array_column($res['data'], 'allocation_number');
        $reportDetail = (new SsyAllocationReportingTable())->whereIn('allocation_number', $allocationNumbers)->get(['allocation_number', 'sku_code'])->toArray();
        $skuCodes = [];
        foreach ($reportDetail as $item){
            $skuCodes[$item['allocation_number']][] = $item['sku_code'];
        }
        $feishuApprovalList = (new SsyFeishuApprovalBindingTable())->whereIn('data_id', $allocationNumbers)->get(['instance_code', 'data_id'])->toArray();
        $approvalIds = array_column($feishuApprovalList, 'instance_code', 'data_id');
        foreach ($res['data'] as &$item){
            $item['sku_code'] = $skuCodes[$item['allocation_number']] ?? [];
            $item['instance_code'] = $approvalIds[$item['allocation_number']] ?? "";
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function detail($allocationNumber)
    {
        return (new SsyAllocationReportingTable())->where('allocation_number', $allocationNumber)->get()->toArray();
    }

    public function apply($param)
    {
        $user = auth()->guard("api")->user()->toArray();
        $allocationNumber="BC".$user['id'].date('YmdHis');
        $totalNum = 0;
        $skuCodes = array_column($param['list'], 'sku_code');
        $list = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["id", "type_no", "product_code", "product_name", "img"])->toArray();
        $listMap = array_column($list, null, "product_code");
        DB::beginTransaction();
        $detailStr = "";
        foreach($param['list'] as $item){
            $num = (Int)$item['num'];
            if($num <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => $item['sku_code'].': 数量错误'];
            }
            //生成调拨明细
            $detailData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $listMap[$item['sku_code']]['product_name'],
                "type_no" => $listMap[$item['sku_code']]['type_no'],
                "img" => $listMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => $num,
                "createtime" => date("Y-m-d H:i:s")
            ];
            $totalNum += $num;
            $createRes = (new SsyAllocationReportingTable())->createData($detailData);
            $detailStr .= '[{"id": "type_name","type":"input","value":"'.$listMap[$item['sku_code']]['product_name'].'"},{"id": "sku_code","type":"input","value":"'.$item['sku_code'].'"},{"id":"num","type":"input","value":"'.$num.'"}],';
            if($createRes['code'] !== 0){
                DB::rollBack();
                return $createRes;
            }
        }
        //生成调拨单
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "adduser" => $user['name'],
            "total_num" => $totalNum,
            "remark" => $param['remark'],
            "createtime" => date("Y-m-d H:i:s")
        ];
        $createRes = (new SsyAllocationReportingListTable())->createData($allocationData);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        $detailStr = trim(rtrim($detailStr,','), '"');
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $isSubject = in_array($user['is_subject'], ['kz', 'mz', 'qyx']) ? 'kz' : $user['is_subject'];
        $fsUserId = $user[$isSubject.'_feishu_user_id'];
        $fsOpenId = $user[$isSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$isSubject]['bc_approval_code'];
        //$fsApprovalCode = "29069D56-F179-4A8A-B3E4-6799C10E8190";
        $date=date("Y-m-d\TH:i:s+H:00",time());
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form"=>'[{"id":"createtime","type":"date","value":"'.$date.'"},{"id":"allocation_number","type":"input","value":"'.$allocationNumber
                .'"},{"id":"num","type":"number","value":"'.$totalNum.'"},{"id": "detaillist","type": "fieldList","value": ['.$detailStr
                .']},{"id":"remark","type":"textarea","value":"'.$param['remark'].'"}]'
        ];
        $res = (new FeishuRepository($isSubject))->createApproval($postData);
        if($res['code'] != '0'){
            DB::rollBack();
            return ['code' => -1, 'msg' => '创建报次审批失败', 'data' => $res];
        }
        $createRes = (new SsyFeishuApprovalBindingTable())->createData([
            "instance_code" => $res['data']['instance_code'],
            "data_id" => $allocationNumber,
            "types" => 6,
            "createtime" => date('Y-m-d H:i:s')
        ]);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        DB::commit();
        return $createRes;
    }
}
